package com.member.common.utils;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * @author thomas
 */
public class TokenUtils {

    public static String createToken() {
        return TokenProccessor.getInstance().makeToken();
    }

    /**
     * 生成token放入session
     *
     * @param request
     * @param tokenServerKey
     */
    public static String createToken(HttpServletRequest request, String tokenServerKey) {

        String token = TokenProccessor.getInstance().makeToken();

        request.getSession().setAttribute(tokenServerKey, token);
        return token;

    }


    /**
     * 移除token
     *
     * @param request
     * @param tokenServerKey
     */

    public static void removeToken(HttpServletRequest request, String tokenServerKey) {

        request.getSession().removeAttribute(tokenServerKey);

    }


    /**
     * 判断请求参数中的token是否和session中一致
     *
     * @param request
     * @param tokenClientkey
     * @param tokenServerkey
     * @return
     */

    public static boolean judgeTokenIsEqual(HttpServletRequest request, String tokenClientkey, String tokenServerkey) {

        String tokenClient = request.getParameter(tokenClientkey);

        if (StringUtils.isEmpty(tokenClient)) {

            return false;

        }

        String tokenServer = (String) request.getSession().getAttribute(tokenServerkey);

        if (StringUtils.isEmpty(tokenServer)) {

            return false;

        }


        if (!tokenServer.equals(tokenClient)) {

            return false;

        }


        return true;

    }
}
